0%

Add Two Numbers

Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode * addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *tmp1 = l1->next, *tmp2 = l2->next;
ListNode *res = new ListNode((l1->val + l2->val) % 10);
ListNode *tmp = res;
int flag = (l1->val + l2->val) > 9 ? 1 : 0;
int k;
while (tmp1&&tmp2)
{
k = tmp1->val + tmp2->val+flag;
tmp->next = new ListNode(k%10);
flag = k / 10;
tmp1 = tmp1->next;
tmp2 = tmp2->next;
tmp = tmp->next;
}
while (tmp1)
{
k = tmp1->val+flag;
tmp->next = new ListNode(k % 10);
flag = k / 10;
tmp1 = tmp1->next;
tmp = tmp->next;
}
while (tmp2)
{
k = tmp2->val+flag;
tmp->next = new ListNode(k % 10);
flag = k / 10;
tmp2 = tmp2->next;
tmp = tmp->next;
}
if(flag)
tmp->next = new ListNode(1);
return res;
}
};
lessons

题目思路其实就像平时算加法一样,从后向前算,考虑进位。开始傻傻地想要把两个list倒过来,得到两个整数进行相加,然后发现长整形的范围远不能满足题目要求,所以才改成了上面那样。看了看别人的代码,发现我的三个while循环实在有些冗杂,可以整理成一个循环,主要考虑对第一个while循环条件进行修改( && -> || ),后面的做法就比较类似了。有点乏了,先不改了,就这样吧。